import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class LayoutRoute extends StatelessWidget {
  LayoutRoute({Key? key}) : super(key: key);

  final logger = Logger(printer: PrettyPrinter());

  @override
  Widget build(BuildContext context) {
    var _children = List.filled(10, const Text("A"));
    return Scaffold(
      appBar: AppBar(
        title: const Text('LayoutBuilder、AfterLayout'),
      ),
      body: Column(
        children: <Widget>[
          SizedBox(
            width: 190,
            child: ResponsiveColumn(
              children: _children,
            ),
          ),
          ResponsiveColumn(
            children: _children,
          ),
          LayoutLogPrint(child: const Text("xx")), // 下面介绍
          Builder(
            builder: (context) {
              return GestureDetector(
                child: const Text('flutter@wendux'),
                onTap: () => logger.i(context.size), //打印 text 的大小
              );
            },
          ),
        ],
      ),
    );
  }
}

class ResponsiveColumn extends StatelessWidget {
  final List<Widget> children;

  const ResponsiveColumn({Key? key, required this.children}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth < 200) {
          return Column(
            children: children,
            mainAxisSize: MainAxisSize.min,
          );
        } else {
          var _children = <Widget>[];
          for (var i = 0; i < children.length; i++) {
            if (i + 1 < children.length) {
              _children.add(
                Row(
                  children: <Widget>[
                    children[i],
                    children[i + 1],
                  ],
                  mainAxisSize: MainAxisSize.min,
                ),
              );
            } else {
              _children.add(children[i]);
            }
          }
          return Column(children: _children, mainAxisSize: MainAxisSize.min);
        }
      },
    );
  }
}

class LayoutLogPrint<T> extends StatelessWidget {
  final logger = Logger(printer: PrettyPrinter());

  LayoutLogPrint({
    Key? key,
    this.tag,
    required this.child,
  }) : super(key: key);

  final Widget child;
  final T? tag; //指定日志tag

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (_, constraints) {
      // assert在编译release版本时会被去除
      assert(() {
        logger.i('${tag ?? key ?? child}: $constraints');
        return true;
      }());
      return child;
    });
  }
}
